class ClickEnlarge extends HTMLElement { constructor() { super(); this.appendChild(ClickEnlarge.template.content.cloneNode(true)); this.mediaQueryList = window.matchMedia('(min-width: 680px)'); this.mediaQueryListener = this.checkMediaQuery.bind(this); this.mediaQueryList.addEventListener('change', this.mediaQueryListener); this.openPopup = this.openPopup.bind(this); } static get template() { if (!this._template) { this._template = document.createElement('template'); this._template.innerHTML = `
`; } return this._template; } connectedCallback() { if (this.dataset.enlarge === 'true') { this.checkMediaQuery(this.mediaQueryList); } } checkMediaQuery(e) { if (e.matches) { if (!this.isMediaQueryMatched) { this.setUpListeners(); this.isMediaQueryMatched = true; } } else { if (this.isMediaQueryMatched) { this.removeEventListener('click', this.openPopup); this.isMediaQueryMatched = false; } } } setUpListeners() { this.popup = this.querySelector('dialog'); this.enlargedImgContainer = this.popup?.querySelector( '.enlarged-image-container' ); this.addEventListener('click', this.openPopup); this.addEventListener('keydown', (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); this.openPopup(); } }); } renderImage() { if (this.cloned) { return; } this.img = this.querySelector('img'); this.cloned = true; const clonedImg = this.img.cloneNode(true); clonedImg.setAttribute('sizes', '100vw'); clonedImg.classList.add('enlarged-image'); this.enlargedImgContainer.appendChild(clonedImg); const internals = this.attachInternals(); internals.ariaDescribedByElements = [this.enlargedImgContainer]; } openPopup() { this.renderImage(); if (this.popup.open) { this.popup.close(); this.removeAttribute('aria-expanded'); } else { this.popup.showModal(); const closeButton = this.popup.querySelector('button'); closeButton.focus(); this.setAttribute('aria-expanded', 'true'); } } disconnectedCallback() { this.removeEventListener('click', this.openPopup); } } if (customElements && !customElements.get('click-enlarge')) { customElements.define('click-enlarge', ClickEnlarge); } else { console.warn('click-enlarge has already been defined'); }